package org.jetlinks.pro.tenant.term;

import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Component
public class AssetsTenantTermBuilder extends AbstractTermFragmentBuilder {

    public static final String termType = "assets-tenant";

    public AssetsTenantTermBuilder() {
        super(termType, "根据资产查询租户信息");
    }

    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {

        PrepareSqlFragments sqlFragments = PrepareSqlFragments.of();

        AssetsTenantTerm tenantTerm = AssetsTenantTerm.of(term);
        if (tenantTerm.isNot()) {
            sqlFragments.addSql("not");
        }
        sqlFragments.addSql("exists(select 1 from s_member_assets ass where"
            , "ass.tenant_id =", columnFullName
        );

        if (StringUtils.hasText(tenantTerm.getAssetType())) {
            sqlFragments.addSql("and ass.asset_type = ?")
                        .addParameter(tenantTerm.getAssetType());
        }
        if (CollectionUtils.isNotEmpty(tenantTerm.getAssetIds())) {
            String[] arr = new String[tenantTerm.getAssetIds().size()];
            Arrays.fill(arr, "?");
            sqlFragments
                .addSql("and ass.asset_id in (", String.join(",", arr), ")")
                .addParameter((Collection)tenantTerm.getAssetIds());
        }

        sqlFragments.addSql(")");

        return sqlFragments;
    }
}
